package com.silence.whereeat.servlet;

import com.silence.whereeat.dao.FoodInfoDao;
import com.silence.whereeat.model.FoodInfo;
import com.silence.whereeat.service.FoodInfoService;
import com.silence.whereeat.utils.GsonUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 获取食品列表
 * Created by 伟阳 on 2015/9/17.
 */
public class GetFoodsServlet extends HttpServlet {

    private FoodInfoService getFoods;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int passage = Integer.parseInt(request.getParameter("passage"));
        List<FoodInfo> foodInfos = getFoods.getFoodInfos(passage);
        PrintWriter out = response.getWriter();
        if (foodInfos.size() > 0) {
            String foodsString = GsonUtils.createJsonString(foodInfos);
            out.println(foodsString);
        } else {
            out.println("null");
        }
        out.flush();
        out.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    public void init() throws ServletException {
        getFoods = new FoodInfoDao();
    }

    @Override
    public void destroy() {
        getFoods.close();
    }
}
